import router from "@/router"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { constantRoutes } from "./index"
import { useUserStore } from "@/store/modules/user"
import { useWebInfoStore } from "@/store/modules/webInfo"
import { ElMessage } from "element-plus"

NProgress.configure({ showSpinner: false })

// 前台页面路径（需要选择用户才能访问）
const webPagePaths = ["/", "/home-article", "/home-detail", "/home-trends", "/home-picture",
  "/home-guestbook", "/home-source", "/home-community", "/home-music", "/home-friendLink", "/home-userinfo"]

// 不需要任何验证的页面
const whiteList = ["/pseudo-login", "/register", "/login", "/404"]

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // 如果是白名单页面，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 判断是前台路由还是后台路由
  const isWebPage = webPagePaths.some(path => to.path.startsWith(path))
  const isAdminPage = constantRoutes.some((item) => item.path === to.path)

  if (isWebPage) {
    // 前台页面：检查是否已选择用户
    const webInfoStore = useWebInfoStore()
    if (!webInfoStore.hasSelectedWebUser) {
      ElMessage.warning("请先选择要访问的用户")
      next("/pseudo-login")
      return
    }
    next()
  } else if (isAdminPage) {
    // 后台管理页面：检查是否有token
    const userStore = useUserStore()
    if (userStore.token) {
      next()
    } else {
      ElMessage.error("请先登录管理后台")
      next("/login")
    }
  } else {
    // 其他页面，直接放行
    next()
  }
})

router.afterEach((to) => {
  NProgress.done()
})
